var express = require("express");
var app = express();

// 设置 handlebars 视图引擎
var handlebars = require("express3-handlebars").create({
  defaultLayout: "main"
});
app.engine("handlebars", handlebars.engine);
app.set("view engine", "handlebars");
var fortune = require("./lib/fortune.js");
var weather = require("./lib/weather.js");
var credentials = require("./lib/credentials.js");
var mail = require("./lib/mail.js");
// 设置端口var var credentials = require('./credentials.js');
app.set("port", process.env.PORT || 3000);
// 加载组件(中间件)
app.use(function(req, res, next) {
  if (!res.locals.partials) res.locals.partials = {};
  res.locals.partials.weather = weather.getWeatherData();
  next();
});
// 测试(中间件)
app.use(function(req, res, next) {
  res.locals.showTests =
    app.get("env") !== "production" && req.query.test === "1";
  next();
});
app.use(require("body-parser")());
app.use(require("cookie-parser")(credentials.cookieSecret));
// 获取表单
app.get("/newsletter", function(req, res) {
  // 我们会在后面学到 CSRF……目前， 只提供一个虚拟值
  res.render("newsletter", { csrf: "CSRF token goes here" });
});
// 处理表单
app.post("/process", function(req, res) {
  console.log("Form (from querystring): " + req.query.form);
  console.log("CSRF token (from hidden form field): " + req.body._csrf);
  console.log("Name (from visible form field): " + req.body.name);
  console.log("Email (from visible form field): " + req.body.email);
  res.redirect(303, "/thank-you");
});
var formidable = require("formidable");
app.get("/postmail", function(req, res) {
  mail.mailTransport.sendMail(
    {
      from: '"JavaScript之禅" <1591128087@qq.com>',
      to: "1591128087@qq.com",
      subject: "Your Meadowlark Travel Tour",
      html: '<h1>Meadowlark Travel</h1>\n<p>Thanks for book your trip with ' +
      'Meadowlark Travel. <b>We look forward to your visit!</b>',
      generateTextFromHtml: true
    },
    (error,info) => {
      if (error) {
        return console.log(error);
      }
      res.send(info);
    }
  );
});
// 获取带文件上传的表单
app.get("/contest/vacation-photo", function(req, res) {
  var now = new Date();
  res.render("contest/vacation-photo", {
    year: now.getFullYear(),
    month: now.getMonth()
  });
});
// 处理带文件上传的表单
app.post("/contest/vacation-photo/:year/:month", function(req, res) {
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files) {
    if (err) return res.redirect(303, "/error");
    console.log("received fields:");
    console.log(fields);
    console.log("received files:");
    console.log(files);
    res.redirect(303, "/thank-you");
  });
});
// 路由设置
app.get("/", function(req, res) {
  res.render("home");
});
app.get("/about", function(req, res) {
  res.render("about", { fortune: fortune.getFortune(),pageTestAboutScript: '/qa/tests-about.js'});
});
app.get("/thank-you", function(req, res) {
  res.render("thank_you");
});
// 404 catch-all 处理器（中间件）
// 静态文件中间件放在首位
app.use(express.static(__dirname + "/public"));
// 404 错误处理器（中间件）
app.use(function(req, res, next) {
  res.status(404);
  res.render("404");
});
// 500 错误处理器（中间件）
app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500);
  res.render("500");
});
app.listen(app.get("port"), function() {
  console.log(
    "Express started on http://localhost:" +
      app.get("port") +
      "; press Ctrl-C to terminate."
  );
});
